package sise.world.gui;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

import org.apache.log4j.Logger;

import sise.world.World;

public class MainFrame extends JFrame {


	private static final long serialVersionUID = -1072081801630756598L;
	private static final Logger logger = Logger.getLogger(MainFrame.class);

	private MapPanel mapPanel;
	private World world;
	
	private class MainFrameKeyListener extends KeyAdapter {
		@Override
		public void keyReleased(KeyEvent keyEvent) {
			// SPACE or ENTER
			if (keyEvent.getKeyCode() == 10 || keyEvent.getKeyCode() == 32) {
				world.nextTurn();
				mapPanel.refresh(world.getWorldMap().getFields());
				}
			}
		}
	
	public MainFrame(World world) {
		logger.info("Creating MainFrame");
		this.world = world;

		setDefaultCloseOperation(EXIT_ON_CLOSE);
		getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
		this.addKeyListener(new MainFrameKeyListener());
		
		// map panel
		mapPanel = new MapPanel(world.getWorldMap().getFields());
		mapPanel.setBorder(BorderFactory.createTitledBorder("Map"));
		getContentPane().add(mapPanel);

		// menubar
		JMenuBar menuBar = new JMenuBar();

		JMenu helpMenu = new JMenu("Help");
		
		JMenuItem controlsMenuItem = new JMenuItem("Instrukcja");
		controlsMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				ControlsHelpFrame.getInstance().setVisible(true);
			}
		});
		JMenuItem autorMenuItem = new JMenuItem("Autorzy");
		autorMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				AutorzyFrame.getInstance().setVisible(true);
					}
				});
				
		menuBar.add(helpMenu);
		helpMenu.add(controlsMenuItem);
		helpMenu.add(autorMenuItem);
		
		setJMenuBar(menuBar);

		// set initial size
		int width = world.getWorldMap().getFields()[0].length * mapPanel.getFieldSize() + 50;
		int height = world.getWorldMap().getFields().length * mapPanel.getFieldSize() + 100;
		setSize(width, height);
	}

	public MapPanel getMapPanel() {
		return mapPanel;
	}

	public void setMapPanel(MapPanel mapPanel) {
		this.mapPanel = mapPanel;
	}

	public World getWorld() {
		return world;
	}

	public void setWorld(World world) {
		this.world = world;
	}

}
